// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/dwio/common/range.h>

namespace kumo::pollux::common {
    Ranges Ranges::filter(const std::function<bool(size_t)> &func) const {
        Ranges ret;
        for (auto &range: ranges_) {
            bool inRun = false;
            size_t runStart = 0;
            for (auto cur = std::get<0>(range), end = std::get<1>(range); cur != end;
                 ++cur) {
                if (func(cur)) {
                    if (!inRun) {
                        inRun = true;
                        runStart = cur;
                    }
                } else if (inRun) {
                    ret.ranges_.emplace_back(runStart, cur);
                    ret.size_ += (cur - runStart);
                    inRun = false;
                }
            }

            if (inRun) {
                ret.ranges_.emplace_back(runStart, std::get<1>(range));
                ret.size_ += (std::get<1>(range) - runStart);
            }
        }
        return ret;
    }
} // namespace kumo::pollux::common
